// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.KdlQffAttach;
import com.javaweb.admin.entity.KdlQffFeedback;
import com.javaweb.admin.mapper.KdlQffAttachMapper;
import com.javaweb.admin.mapper.KdlQffFeedbackMapper;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.DynamicDataSource;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.constant.FormtableMain12974Constant;
import com.javaweb.admin.entity.FormtableMain12974;
import com.javaweb.admin.mapper.FormtableMain12974Mapper;
import com.javaweb.admin.query.FormtableMain12974Query;
import com.javaweb.admin.service.IFormtableMain12974Service;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.service.IDictDataService;
import com.javaweb.system.utils.ShiroUtils;
import com.javaweb.admin.vo.formtablemain12974.FormtableMain12974InfoVo;
import com.javaweb.admin.vo.formtablemain12974.FormtableMain12974ListVo;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.seegw.shaphar.IKDLService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
  * <p>
  *  服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2024-08-02
  */
@Service
public class FormtableMain12974ServiceImpl extends BaseServiceImpl<FormtableMain12974Mapper, FormtableMain12974> implements IFormtableMain12974Service {

    @Autowired
    private FormtableMain12974Mapper formtableMain12974Mapper;

    @Autowired
    private KdlQffFeedbackMapper kdlQffFeedbackMapper;

    @Autowired
    private IKDLService kdlService;

    @Autowired
    private KdlQffAttachMapper kdlQffAttachMapper;

    @Autowired
    private IDictDataService dictDataService;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.JZT)
    public JsonResult getList(BaseQuery query) {
        FormtableMain12974Query formtableMain12974Query = (FormtableMain12974Query) query;
        // 查询条件
        QueryWrapper<FormtableMain12974> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<FormtableMain12974> page = new Page<>(formtableMain12974Query.getPage(), formtableMain12974Query.getLimit());
        IPage<FormtableMain12974> pageData = formtableMain12974Mapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            FormtableMain12974ListVo formtableMain12974ListVo = Convert.convert(FormtableMain12974ListVo.class, x);
            return formtableMain12974ListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        FormtableMain12974 entity = (FormtableMain12974) super.getInfo(id);
        // 返回视图Vo
        FormtableMain12974InfoVo formtableMain12974InfoVo = new FormtableMain12974InfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, formtableMain12974InfoVo);
        return formtableMain12974InfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(FormtableMain12974 entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateUser(ShiroUtils.getUserId());
            entity.setUpdateTime(DateUtils.now());
        } else {
            entity.setCreateUser(ShiroUtils.getUserId());
            entity.setCreateTime(DateUtils.now());
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(FormtableMain12974 entity) {
        entity.setUpdateUser(1);
        entity.setUpdateTime(DateUtils.now());
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public void sendOaToKdl() {
        try {
            String switchQff = this.getDicStatus("SWITCH", "SWITCH_QFF", DataSourceType.BIP);
            boolean switchQffFlag = switchQff.equals("1") ? true : false;
            if (!switchQffFlag){
                return;
            }
            DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
            List<FormtableMain12974> formtableList = formtableMain12974Mapper.selectList(new QueryWrapper<FormtableMain12974>()
                    .eq("ftriggerflag", "2").eq("def10","READ"));
            if (CollectionUtils.isEmpty(formtableList)) {
                return;
            }
            for (FormtableMain12974 form : formtableList) {
                DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
                List<KdlQffFeedback> qffs = kdlQffFeedbackMapper.selectList(new QueryWrapper<KdlQffFeedback>().eq("principalorderno", form.getDjid()));
                if (CollectionUtils.isEmpty(qffs)) {
                    continue;
                }
                for (KdlQffFeedback qff : qffs) {
                    if (!StringUtils.isEmpty(form.getBdef1())) {
                        qff.setTolocation("0".equals(form.getBdef1()) ? "1008" : "1010");
                    }
                    if (!StringUtils.isEmpty(form.getBdef2())) {
                        qff.setFeedback("0".equals(form.getBdef2()) ? "不同意" : "同意");
                    }
                    qff.setUpdateTime(DateUtils.now());
                    qff.setOperTime(DateUtils.getDate());
                    qff.setOperUser("董晨贻");
                    //更新反馈信息
                    DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
                    kdlQffFeedbackMapper.updateById(qff);
                    //发送反馈至kdl
                    kdlService.uploadExceptionFeedback(qff.getId());
                }
                form.setDef10("END");
                DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
                formtableMain12974Mapper.updateById(form);
            }
        } catch (Exception e) {
            log.error("sendOaToKdl 更新状态报错");
            log.error(e.getMessage());
        }

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.BIP)
    public void updateFtriggerflag() {
        try {
            String switchQff = this.getDicStatus("SWITCH", "SWITCH_QFF", DataSourceType.SINESYS);
            boolean switchQffFlag = switchQff.equals("1") ? true : false;
            if (!switchQffFlag){
                return;
            }
            DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
            List<FormtableMain12974> formtableList = formtableMain12974Mapper.selectList(new QueryWrapper<FormtableMain12974>()
                    .eq("ftriggerflag", "1").eq("requestid","0").eq("def10","INITIAL"));
            if (CollectionUtils.isEmpty(formtableList)) {
                return;
            }
            for (FormtableMain12974 form : formtableList) {
                DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
                List<KdlQffFeedback> qffs = kdlQffFeedbackMapper.selectList(new QueryWrapper<KdlQffFeedback>().eq("principalorderno", form.getDjid()));
                if (CollectionUtils.isEmpty(qffs)) {
                    continue;
                }
                Set<String> set = qffs.stream().map(KdlQffFeedback::getQffno).collect(Collectors.toSet());
                DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
                List<KdlQffAttach> attachList = kdlQffAttachMapper.selectList(new QueryWrapper<KdlQffAttach>().in("qffno", set));
                if (CollectionUtils.isEmpty(attachList)) {
                    continue;
                }
                // 该QFF的异常反馈全部下载好，更新oa可读取状态
                boolean flag = attachList.stream().allMatch(o -> "已下载".equals(o.getStatus()));
                if (flag) {
                    form.setFtriggerflag("0");
                    form.setDef10("READ");
                    DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
                    formtableMain12974Mapper.updateById(form);
                }
            }
        } catch (Exception e) {
            log.error("updateFtriggerflag 更新状态报错");
            log.error(e.getMessage());
        }
    }

    private String getDicStatus(String dicCode, String dicDataCode, DataSourceType dataSourceType) {
        DynamicDataSource.setDataSource("system");
        String status = dictDataService.getDicStatus(dicCode, dicDataCode);
        DynamicDataSource.setDataSource(dataSourceType.getName());
        return status;
    }
}